package com.finalab.website.controller;


import com.finalab.website.constant.ResponseCode;
import com.finalab.website.model.Project;
import com.finalab.website.service.ProjectService;
import com.finalab.website.util.CosClientUtil;
import com.finalab.website.util.FileNameUtil;
import com.finalab.website.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/file")
public class FileController {
    @Autowired
    ProjectService projectService;

    @RequestMapping(value = "/downloadPicture")
    public void downloadPicture(int pictureType, int id,
                                PrintWriter out){
        Project project = projectService.selectById(id);
        int size = project.getProPicture();
        String name;
        List<String> url = new ArrayList<>();
        for(int i = 1;i <= size;i++){
            name = FileNameUtil.pictureName(pictureType, i, id);
            url.add(CosClientUtil.GenerateSimplePresignedDownloadUrl(name));
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("urls", url);
        ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, map);
    }

    @RequestMapping(value = "/uploadPicture")
    public void uploadPicture(MultipartFile[] file, int pictureType,
                              int id, PrintWriter out){
        Project project = projectService.selectById(id);
        int size = project.getProPicture() + 1;
        String name;
        for(int i = size;i < file.length + size;i++){
            name = FileNameUtil.pictureName(pictureType, i, id);
            CosClientUtil.uploadFile(name,file[i]);
        }
        project.setProPicture(file.length+size-1);
        projectService.update(project);
        ResponseUtil.responseCode(out, ResponseCode.REQUEST_SUCCESSED);
    }
}
